#include"../source/socket.hpp"
#include"../source/server.hpp"
#include"../source/connection.hpp"
#include"../source/buffer.hpp"
#include"../source/acceptor.hpp"
#include"../source/LoopThread.hpp"

/*用于管理所有的连接对象*/
std::unordered_map<uint64_t,PtrConnection> _conns;
uint64_t conn_id=0;

// EventLoop loop;
EventLoop base_loop;//专门在主线程里用来执行监听事件的
// std::vector<LoopThread> threads(2);
// int next_loop=0;
LoopThreadPool* loop_pool;



void ConnectionDestroy(const PtrConnection& conn){
    _conns.erase(conn->Id());
}

void OnConnected(const PtrConnection& conn){
    DLOG("NEW CONNECTION:%p",conn.get());
}

void MessageHandler(const PtrConnection&conn,Buffer*buffer){
    DLOG("%s",buffer->ReadPosition());
    buffer->MoveReadOffset(buffer->ReadAlbeSize());
    std::string str="hello";
    conn->Send(str.c_str(),str.size());
    // conn->Shutdown();
}

// void Acceptor(Channel* listen_channel,EventLoop*loop){
void NewConnection(int fd){  
    conn_id++;
    // PtrConnection conn(new Connection(&loop,conn_id,fd));
    // next_loop=(next_loop+1)%2;
    // PtrConnection conn(new Connection(threads[next_loop].GetLoop(),conn_id,fd));
    PtrConnection conn(new Connection(loop_pool->NextLoop(),conn_id,fd));
    
    conn->SetConnectedCallback(std::bind(OnConnected,std::placeholders::_1));
    conn->SetMessageCallback(std::bind(MessageHandler,std::placeholders::_1,std::placeholders::_2));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy,std::placeholders::_1));
    
    conn->EnableInactiveRelease(10);//启动非活跃超时销毁功能
    conn->Establish();//就绪初始化

    _conns.insert(std::make_pair(conn_id,conn));
    DLOG("NEW--------------");
}
/*主线程是只负责获取新连接的线程，和实际处理新连接的线程不是同一个线程*/
/*我们获取新连接进行监听连接的线程是主线程，而处理我们的新连接通信的线程是从属线程*/
/*主从Reactor模型：主线程只负责对监听套接字的处理，获取新连接，保证连接的获取效率，不会因为业务的处理而导致无法去获取新连接*/
/*而从属Reactor，获取新连接会被分配给从属Reactor，让从属线程对他进行事件监控，事件的处理，以及业务的处理*/
int main()
{   
    loop_pool=new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    // Acceptor acceptor(&loop,8081);
    Acceptor acceptor(&base_loop,8081);
    acceptor.SetAccept(std::bind(NewConnection,std::placeholders::_1));
    acceptor.Listen();
    // while(1)
    // {
    base_loop.Start();//在EventLoop内部已经加入循环
    // }

    return 0;
}